<template>
  <div class="panel-table" style="padding: 0 20px">
    <rj-table
      :columns="columns"
      :data-source="data"
      :pagination="pagination"
      :loading="loading"
      :filtercolumns="true"
      @refeshTable="refeshTable"
      :scroll="{ x: 1800 }"
      bordered
      @change="handleTableChange"
    >
      <div slot="customBlock" class="form-proup">
        <a-space size="middle">
          <a-select
            default-value=""
            style="width: 120px"
            :dropdownMatchSelectWidth="false"
            @change="handleTypeChange"
          >
            <a-select-option value="">
              {{ $t('upgradeLog.selectOperationType') }}
            </a-select-option>
            <a-select-option value="DEVICE">
              {{ $t('upgradeLog.specifiedDeviceUpgrade') }}
            </a-select-option>
            <a-select-option value="FILTER">
              {{ $t('upgradeLog.specifiedConditionsUpgrade') }}
            </a-select-option>
          </a-select>
          <a-select
            default-value=""
            style="width: 120px"
            @change="handleStatusChange"
          >
            <a-select-option value="">
              {{ $t('upgradeLog.selectUpgradeStatus') }}
            </a-select-option>
            <a-select-option value="EXECUTING">
              {{ $t('upgradeLog.ing') }}
            </a-select-option>
            <a-select-option value="FINISHED">
              {{ $t('upgradeLog.finish') }}
            </a-select-option>
          </a-select>
          <a-range-picker
            :open="open"
            :placeholder="[$t('public.startDate'), $t('public.endDate')]"
            format="YYYY/MM/DD HH:mm:ss"
            @change="onPickerChange"
            @openChange="openChange"
          >
            <a-icon slot="suffixIcon" type="calendar" />
          </a-range-picker>
          <a-button type="primary" icon="search" @click="inquireLog">
            {{ $t('public.search') }}
          </a-button>
        </a-space>
      </div>
      <template slot="bewrite" slot-scope="text, record">
        <span>{{ record.taskForce }}</span
        ><br />
        <span>{{ record.allCount }}</span>
      </template>
      <template slot="execstatus" slot-scope="text, record">
        <span>{{ record.sufaCount }}</span
        ><br />
        <span style="color: #999">{{ record.exabortCount }}</span>
      </template>
      <template slot="operate" slot-scope="text, record">
        <a-space>
          <!-- <icon-font
            type="ic-details"
            title="查看详情"
            
          /> -->
          <a @click="showModal(record)">{{ $t('upgradeLog.viewDetails') }}</a>
          <a-popconfirm
            :title="$t('upgradeLog.confirmStopExe')"
            :ok-text="$t('public.check')"
            :cancel-text="$t('public.cancel')"
            @confirm="confirmAbort(record)"
          >
            <!-- <icon-font type="ic-termination" title="停止" /> -->
            <a>{{ $t('upgradeLog.stopUpgrade') }}</a>
          </a-popconfirm>
          <a-popconfirm
            :title="$t('upgradeLog.isReExec')"
            :ok-text="$t('public.check')"
            :cancel-text="$t('public.cancel')"
            @confirm="confirmRestart(record)"
          >
            <!-- <icon-font type="ic-redo" title="重试" /> -->
            <a>{{ $t('upgradeLog.retry') }}</a>
          </a-popconfirm>
        </a-space>
        <rj-modal
          :title="$t('upgradeLog.upgrteLogDetail')"
          :visible="visible == record.key"
          width="1350px"
          :footer="null"
          :maskClosable="false"
          @cancel="handleCancel"
        >
          <device-view :jobid="jobid" />
        </rj-modal>
      </template>
    </rj-table>
  </div>
</template>

<script>
import moment from 'moment';
import { requestHttp, maccApi } from '@utils/index';
import { RjTable, RjModal } from '@components';
import { columns } from '../columns/columns.js';
import { Deviceview } from './index';
export default {
  data() {
    return {
      open: false,
      visible: -1,
      jobid: '',
      loading: false,
      data: [],
      current: 1,
      pagination: {},
      logparams: {
        page: 1,
        per_page: 10,
        type: '',
        status: '',
        start_time: '',
        end_time: '',
      },
    };
  },
  computed: {
    columns() {
      columns.forEach((item) => {
        item.title = this.$t(`upgradeLog.${item.dataIndex1}`);
      });
      return columns;
    },
  },
  watch: {
    columns() {
      this.getLogList();
    },
  },
  components: {
    'rj-table': RjTable,
    'rj-modal': RjModal,
    'device-view': Deviceview,
  },
  mounted() {
    this.getLogList();
  },

  methods: {
    moment,

    //取得升级日志列表
    async getLogList() {
      this.data = [];
      this.pagination = { total: 0 };
      this.loading = true;
      let url = this.callLogurl();
      const res = await requestHttp({
        api: `${maccApi.JOB_GET_API}${url}`,
        method: 'GET',
      });
      if (res.code != 0) {
        this.$message.error(
          res.msg || this.$t('upgradeLog.getUpgradeLogFailed')
        );
        return;
      }
      if (res.totalCount && res.totalCount > 0) {
        let page = {
          current: this.current,
          total: res.totalCount,
          showSizeChanger: true,
          showQuickJumper: true,
        };
        this.pagination = page;
        let arr = [];
        for (const key in res.jobList) {
          let obj = {};
          obj.key = key;
          obj.upgradeJobId = res.jobList[key].id;
          obj.userName = res.jobList[key].userName;
          obj.taskForce = `${this.$t('upgradeLog.upgradeTaskGroup')}${
            res.jobList[key].createTime
          }`;
          obj.allCount = `${this.$t('upgradeLog.selectedDevice')}${
            res.jobList[key].allCount
          }${this.$t('upgradeLog.upgradeDevice')}`;
          obj.targetVersion = this.getTargetVersion(
            res.jobList[key].targetVersion
          );
          if (res.jobList[key].status == 'FINISHED') {
            obj.status = this.$t('public.finish');
          }
          if (res.jobList[key].status == 'EXECUTING') {
            obj.status = this.$t('upgradeLog.ing');
          }
          // let opertime = this.getSpecifiedTime(res.jobList[key].createTime);
          // obj.createTime = `${opertime.year}-${opertime.month}-${opertime.day} ${opertime.hour}:${opertime.minutes}`;
          obj.createTime = this.moment(res.jobList[key].createTime).format(
            'YYYY/MM/DD HH:mm:ss'
          );
          obj.retryTimes = res.jobList[key].retryTimes;
          // let startdate = this.getSpecifiedTime(res.jobList[key].beginDate);
          // obj.beginDate = `${startdate.year}-${startdate.month}-${startdate.day}`;
          obj.beginDate = this.moment(res.jobList[key].beginDate).format(
            'YYYY/MM/DD'
          );

          obj.statusDesc = this.getFormatData(res.jobList[key].statusDesc);
          obj.sufaCount = `${this.$t('upgradeLog.successOrFail')}${
            res.jobList[key].successCount
          }/${res.jobList[key].failCount}`;
          obj.exabortCount = `${this.$t('upgradeLog.executingOrAbort')}${
            res.jobList[key].executingCount
          }/${res.jobList[key].abortCount}`;
          arr.push(obj);
        }
        this.loading = false;
        this.data = arr;
      } else {
        this.loading = false;
        this.data = [];
        this.pagination = { total: 0 };
      }
    },

    //设备升级终止
    async abortJob(jobId) {
      const res = await requestHttp({
        api: `${maccApi.JOB_ABORT_POST_API}${jobId}`,
        method: 'POST',
        params: {},
      });
      if (res.code != 0) {
        this.$message.error(
          res.msg || this.$t('upgradeLog.deviceUpgradeStopFailed')
        );
      } else {
        this.$message.success(this.$t('upgradeLog.stopSucceeded'));
      }
    },

    //设备重新升级
    async restartJob(jobId) {
      const res = await requestHttp({
        api: `${maccApi.JOB_RESTART_POST_API}${jobId}`,
        method: 'POST',
        params: {},
      });
      if (res.code != 0) {
        this.$message.error(
          res.msg || this.$t('upgradeLog.deviceReupgradeFailed')
        );
      } else {
        this.$message.success(this.$t('upgradeLog.executeSuccess'));
      }
    },

    //返回升级日志URL
    callLogurl() {
      let url = `?page=${this.logparams.page}&per_page=${this.logparams.per_page}`;
      if (this.logparams.type) {
        url = url + '&type=' + this.logparams.type;
      }
      if (this.logparams.status) {
        url = url + '&status=' + this.logparams.status;
      }
      if (this.logparams.start_time) {
        url = url + '&start_time=' + this.logparams.start_time;
      }
      if (this.logparams.end_time) {
        url = url + '&end_time=' + this.logparams.end_time;
      }
      return url;
    },

    //获取格式数据
    getFormatData(str) {
      let index = str.indexOf(']');
      let arr = str
        .substring(index + 1)
        .replace(/\s*/g, '')
        .replace(/-/g, ':')
        .split(':');
      let newarr = arr.map((x) => {
        return x.length == 2 ? x : `0${x}`;
      });
      return `${newarr[0]}:${newarr[1]}-${newarr[2]}:${newarr[3]}`;
    },

    getTargetVersion(str) {
      let index = str.indexOf(';');
      let result = '';
      if (index !== -1) {
        result = str.substring(0, index);
      } else {
        result = str;
      }
      return result;
    },

    //升级任务表格分页变化时触发
    handleTableChange(pagination) {
      this.current = pagination.current;
      this.logparams.page = pagination.current;
      this.logparams.per_page = pagination.pageSize;
      this.getLogList();
    },

    //操作类型切换
    handleTypeChange(value) {
      this.logparams.type = value;
    },

    //升级状态切换
    handleStatusChange(value) {
      this.logparams.status = value;
    },

    //修改时间日期
    onPickerChange(date, dateString) {
      this.open = false;
      this.logparams.start_time = new Date(Date.parse(dateString[0])).getTime();
      this.logparams.end_time = new Date(Date.parse(dateString[1])).getTime();
    },

    //弹出日历和关闭日历的回调
    openChange() {
      this.open = !this.open;
    },

    //升级任务查询
    inquireLog() {
      this.current = 1;
      this.logparams.page = 1;
      this.logparams.per_page = 10;
      this.getLogList();
    },

    //弹出对话框
    showModal(record) {
      this.visible = record.key;
      this.jobid = record.upgradeJobId.toString();
    },

    //关闭对话框
    handleCancel() {
      this.visible = -1;
    },

    //设备重新升级
    confirmRestart(recrod) {
      this.restartJob(recrod.upgradeJobId);
    },

    //设备升级终止
    confirmAbort(recrod) {
      this.abortJob(recrod.upgradeJobId);
    },

    //刷新
    refeshTable() {
      this.getLogList();
    },
  },
};
</script>

<style lang="less" scoped>
.form-proup {
  line-height: 32px;
  margin-bottom: 20px;
  display: flex;
  flex-direction: row;
}

.panel-table {
  /deep/ .ant-table-thead > tr > th {
    padding: 5px 16px;
  }

  /deep/ .ant-table-tbody > tr > td {
    padding: 5px 16px;
  }
}
</style>
